package log

import (
	"dev.ixmxm.top/rms/utils/buffer"
	"fmt"
	"time"
)

func NewConsoleEncodeWriter() EncodeWriter {
	return new(consoleEncodeWriter)
}

type consoleEncodeWriter struct {
}

func (v *consoleEncodeWriter) Encoder(entry Entry) (*buffer.Buffer, error) {
	color := Green
	switch entry.Level {
	case DebugLevel:
		color = Blue
	case InfoLevel:
		color = Green
	case WarnLevel:
		color = Yellow
	case ErrorLevel:
		color = Red
	case DPanicLevel, PanicLevel:
		color = Cyan
	case FatalLevel:
		color = PurplishRed
	}
	line := ColorSprintf(color, "[%s] [%s] [%s] [%s] [%s] %s\n", entry.LoggerName, entry.Time.Local().Format(time.RFC3339Nano), entry.Level.CapitalString(), entry.TraceID, entry.Caller, entry.Message)
	buf := buffer.Get()

	defer buf.Free()
	if entry.Stack != "" {
		line += entry.Stack
		line += "\n"
	}
	buf.AppendString(line)
	return buf, nil
}

func (v *consoleEncodeWriter) Write(p []byte) (int, error) {
	fmt.Print(string(p))
	return len(p), nil
}
